package com.atguigu.tingshu.order.task;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.order.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Slf4j
public class RedisDelayHandler {

    @Autowired
    private RedissonClient redissonClient ;

    @Autowired
    private OrderInfoService orderInfoService ;

    @Scheduled(cron = " * * * * * ? ")
    public void redisDelayQueueHandler() {

        // 获取分布式锁
        RLock rLock = redissonClient.getLock("queue:order:cancel:lock");
        boolean tryLock = rLock.tryLock();
        if(tryLock) {

            // log.info(Thread.currentThread().getId() + "该线程获取到了分布式锁...");

            try {
                RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque(RedisConstant.QUEUE_ORDER_CANCEL_PREFIX);
                String orderNo = blockingDeque.poll();// 获取延迟任务数据，当前方法不具备阻塞效果
                if(!StringUtils.isEmpty(orderNo)) {
                    orderInfoService.cancelOrder(orderNo) ;
                    log.info("订单超时未支付自动去取了订单, orderNo: {} " , orderNo );
                }
            }catch (Exception e) {
                e.printStackTrace();
            }finally {
                // log.info(Thread.currentThread().getId() + "该线程释放了分布式锁...");
                rLock.unlock();
            }

        }

    }

}
